package com.lw.sbdemo2.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>标题: HttpClient工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2017</p>
 * <p>公司: 智业软件</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date: 2017-06-14 16:51
 */
public class LwHttpClientUtil {

    private static RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(60000)
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .build();

    public LwHttpClientUtil() {

    }

    /**
     * 发送Get请求
     *
     * @return
     */
    public static String sendHttpGet(String httpUrl) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity;
        String responseContent = null;

        try {
            HttpGet httpGet = new HttpGet(httpUrl);
            if (httpUrl.startsWith("https")) {
                // 执行 Https 请求.
                PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
                DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
                httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            } else {
                // 执行 Http 请求.
                httpClient = HttpClients.createDefault();
            }
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return responseContent;
    }

    /**
     * 发送Post请求
     *
     * @param httpUrl
     * @param headers
     * @param params
     * @return
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> headers, Map<String, String> params) {

        HttpPost httpPost = new HttpPost(httpUrl);

        //拼接参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (params != null) {
            for (String key : params.keySet()) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            //拼接头文件
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPostHandle(httpPost);
    }

    public static void main(String[] args) {
    }

    /**
     * 发送Post请求(JSON字符串)
     * 接口要用 @RequestBody String request 接收
     *
     * @return
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> headers, String jsonStr) {

        HttpPost httpPost = new HttpPost(httpUrl);
        //拼接参数
        httpPost.setHeader("Content-type", "application/json");

        //json字符串以实体的实行放到post中
        httpPost.setEntity(new StringEntity(jsonStr, Charset.forName("utf-8")));

        //拼接头文件
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpPost.addHeader(key, headers.get(key));
            }
        }
        return sendHttpPostHandle(httpPost);
    }

    /**
     * 发送Post请求
     *
     * @param httpPost
     * @return
     */
    private static String sendHttpPostHandle(HttpPost httpPost) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity;
        String responseContent = null;
        try {
            httpClient = HttpClients.createDefault();
            //httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
}
